package com.xiaojie.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description: reids工具类
 * @author xiaojie
 * @date 2022/5/9 15:02
 * @version 1.0
 */
@Component
public class RedisToken {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取Token
     *
     * @return
     */
    public String getToken() {
        //1. 使用uuid生成Token
        String token = UUID.randomUUID().toString().replace("-", "");
        //2. 将Token存放到Redis中
        setString(token, token, 7200l);
        return token;
    }

    public Boolean findByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        String redisToken = getString(token);
        if(StringUtils.isEmpty(redisToken)){
            return  false;
        }
        delKey(redisToken);
        return  true;
    }


    private void setString(String key, Object data, Long timeout) {
        if (data instanceof String) {
            String value = (String) data;
            stringRedisTemplate.opsForValue().set(key, value);
        }
        if (timeout != null) {
            stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
    }

    private String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    private void delKey(String key) {
        stringRedisTemplate.delete(key);
    }

}
